import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPFile;



public class FtpMain {

	public static void main(String[] args) {
		if (args.length == 1) {
			if (args[0].equalsIgnoreCase("-h")) {
				System.out.println("usage: FtpMain 1.1.1.1 8080 username password [/ftpDirectory]");
				System.out.println("usage(test default site): FtpMain test");
				return;
			}else if (args[0].equalsIgnoreCase("test")) {
				args = new String[5];
				args[0] = "202.38.97.197"; //202.38.97.197 ftp://ftp.pku.edu.cn
				args[1] = "21";
				args[2] = "anonymous";
				args[3] = "ftp4j";
				args[4] = "/pub/";
				doFtp(args);
				return;
			}
		}		
		
		if (args.length < 2) {
			System.out.println("wrong args. use -h to get usage.");
			return;
		}
		
		doFtp(args);
	}

	private static void doFtp(String[] args) {
		FTPClient client = null;
		try {
			client = new FTPClient();
			client.connect(args[0], Integer.parseInt(args[1]));
			if (args.length > 3) {
				client.login(args[2], args[3]);
				System.out.println("login success to " + args[0]);
			}
			client.setPassive(false);
			String currentDirectory = client.currentDirectory();
			System.out.println("currentDirectory:" + currentDirectory);
			FTPFile[] ftpFiles;
			try {
				ftpFiles = client.list();
				for (FTPFile ftpFile : ftpFiles) {
					System.out.println("\t" + ftpFile.getName());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			if (args.length >= 5) {
				client.changeDirectory(args[4]);
				System.out.println("changeDirectory to " + client.currentDirectory());
				try {
					ftpFiles = client.list();
					System.out.println("list " + args[4] + " files: ");
					for (FTPFile ftpFile : ftpFiles) {
						System.out.println("\t" + ftpFile.getName());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (client != null) {
				try {
					client.disconnect(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

}
